package com.yym.ssh;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public class Test {

	private static String host = "192.168.198.143";
	private static String username = "root";
	private static String password = "1";
	private Connection conn = null;

	public Test(String host, String username, String password) {
		super();
		this.host = host;
		this.username = username;
		this.password = password;

		conn = new Connection(host);

		try {
			conn.connect();
			System.out.println("ok");
			boolean isAuthentied = conn.authenticateWithPassword(username,
					password);
			if (!isAuthentied) {

				System.out.println("Authenticated failed...");
			}

		} catch (IOException e) {
			System.err.println("error");
		}

	}

	public void testOpt() {
		try {
			Session sess = conn.openSession();
			sess.execCommand("ls -l");

			InputStream so = sess.getStdout();
			InputStream err = sess.getStderr();
			OutputStream out = sess.getStdin();

			byte[] bufferout = new byte[500];
			byte[] buffererr = new byte[500];

			int buffoutlength=0;
			buffoutlength=so.read(bufferout);
			if(buffoutlength!=-1){
				System.out.println("#2:"+new String(bufferout,0,buffoutlength));
			}
			
			int length = 0;
			length = err.read(buffererr);
			if (length != -1) {
				System.out.println("#1:" + new String(buffererr, 0, length));

			}
			
			

		} catch (IOException e) {
			System.out.println("open session error");
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		new Test(host, username, password).testOpt();
	}

}
